package v1

import (
	"github.com/gin-gonic/gin"
	"melon/server/constant"
	"melon/server/model"
	"melon/server/service"
	"melon/server/utils/response"
)

type MyQiniuFile struct {
}

func (q *MyQiniuFile) Show(context *gin.Context) {
	showList := service.CreateQiniuCurdFactory("MyQiniu").GetFileList("")
	if showList != nil {
		response.Success(context, constant.CurdStatusOkMsg, showList)
	} else {
		response.Fail(context, constant.CurdSelectFailCode, constant.CurdSelectFailMsg, "")
	}
}

func (q *MyQiniuFile) Upload(context *gin.Context) {
	formFile, header, _ := context.Request.FormFile("file")
	if uploadFile, err := service.CreateQiniuCurdFactory("MyQiniu").UploadFile(header.Filename, formFile, header.Size); err == nil {
		response.Success(context, constant.CurdStatusOkMsg, uploadFile)
	} else {
		response.Fail(context, constant.FilesUploadFailCode, constant.FilesUploadFailMsg, "")
	}
}

func (q *MyQiniuFile) Download(context *gin.Context) {
	filename := context.Param("filename")
	if downloadFile := service.CreateQiniuCurdFactory("MyQiniu").DownloadFile(filename); downloadFile != "" {
		response.Success(context, constant.CurdStatusOkMsg, downloadFile)
	} else {
		response.Fail(context, constant.FilesUploadFailCode, constant.FilesUploadFailMsg, "")
	}
}

func (q *MyQiniuFile) Delete(context *gin.Context) {
	filename := context.Param("filename")
	if err := service.CreateQiniuCurdFactory("MyQiniu").DeleteFile(filename); err == nil {
		response.Success(context, constant.CurdStatusOkMsg, "")
	} else {
		response.Fail(context, constant.FilesUploadFailCode, constant.FilesUploadFailMsg, "")
	}
}

func (q *MyQiniuFile) BatchDelete(context *gin.Context) {
	var req model.Params
	// 绑定参数
	if err := context.ShouldBindJSON(&req); err != nil {
		response.Fail(context, constant.ValidatorParamsCheckFailCode, constant.ValidatorParamsCheckFailMsg, "")
	}

	factory := service.CreateQiniuCurdFactory("MyQiniu")
	for _, value := range req.Ids {
		err := factory.DeleteFile(value)
		if err != nil {
			response.Fail(context, constant.FilesUploadFailCode, constant.FilesUploadFailMsg, "")
			return
		}
	}
	response.Success(context, constant.CurdStatusOkMsg, "")
}
